package com.goldgov;

import com.goldgov.kduck.auth.AuthUserInfo;
import com.goldgov.kduck.auth.AuthUserInfoAdditional;
import com.goldgov.kduck.auth.AuthUserService;
import com.goldgov.kduck.module.user.service.User;
import com.goldgov.kduck.module.user.service.UserService;
import com.kcloud.ms.authentication.baseaccount.service.Account;
import com.kcloud.ms.authentication.baseaccount.service.AccountCredential;
import com.kcloud.ms.authentication.baseaccount.service.AccountCredentialService;
import com.kcloud.ms.authentication.baseaccount.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @deprecated 未来会使用kduck-security代替。
 */
@Component
public class AuthUserServiceImpl implements AuthUserService, AuthUserInfoAdditional {

    @Autowired
    private AccountCredentialService accountCredentialService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserService userService;

    @Override
    public User getAuthUser(String accessToken) {
        OAuth2AccessToken oAuth2Access = tokenStore.readAccessToken(accessToken);
        Map<String, Object> additionalInformation = oAuth2Access.getAdditionalInformation();
        String credentialName = additionalInformation.get("user_name").toString();
        return getUser(credentialName);
    }

    /**
     * 根据登录名获取用户信息
     * @param credentialName
     * @return
     */
    private User getUser(String credentialName){
        if(StringUtils.isEmpty(credentialName)){
            return null;
        }
        AccountCredential accountCredential = accountCredentialService.getCredentialByName(credentialName);
        if(accountCredential == null){
            return null;
        }
        Account account = accountService.getAccount(accountCredential.getAccountId());
        if(account == null || StringUtils.isEmpty(account.getUserId())){
            return null;
        }
        User user = userService.getUser(account.getUserId());
        return user;
    }

    @Override
    public void additional(AuthUserInfo authUserInfo, HttpServletRequest httpServletRequest) {
        //FIXME 项目组扩展使用，用于放一些用户信息，不推荐使用Session
        authUserInfo.setDetailsItem("扩展信息KEY","扩展信息VALUE");
    }
}
